package com.dayou.service.impl;

import com.dayou.bean.*;
import com.dayou.common.core.text.Convert;
import com.dayou.common.exception.BusinessException;
import com.dayou.common.utils.StringUtils;
import com.dayou.mapper.InterviewMapper;
import com.dayou.service.IInterviewService;
import com.dayou.service.MqService;
import com.dayou.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class InterviewService implements IInterviewService {
    @Autowired
    private InterviewMapper dao;
    @Autowired
    private RoomService roomService;
    @Autowired
    private SysDeptService deptService;
    @Autowired
    private BringRecordService bringRecordService;
    @Autowired
    private MqService mqService;
    @Value("${interview.module-name}")
    private String moduleName;
    @Override
    public List<InterviewerRecord> list(InterviewerRecord record) {
        SysUser loginUser = UserUtil.getUser();
        Integer deptId = loginUser.getDeptId();
        SysDept dept = deptService.selectSysDeptById(deptId);
        List<InterviewerRecord> records = null;
        Map<String,Object> params = new HashMap<>();
        if ("自助机".equals(dept.getName())) {
            params.put("state",0);
            record.setParams(params);
            records = dao.list(record);
        } else if ("讯问室".equals(dept.getName())) {
            String roomNo = loginUser.getNickname().substring(0,3);
            Room roomConditiron = new Room();
            roomConditiron.setNumber(roomNo);
            List<Room> rooms = roomService.selectRoomList(roomConditiron);
            if (rooms.size() > 0) {
                Integer roomId = rooms.get(0).getArdId();
                params.put("unDone",true);
                params.put("roomId",roomId);
                record.setParams(params);
                records = dao.list(record);
                if(records.size() > 1){
                    throw new BusinessException("记录数目异常");
                }
            } else {
                throw new BusinessException("未查询到当前房间信息，请检查账号");
            }
        }
        return records;
    }

    @Override
    @Transactional
    public boolean insertInterviewerRecord(InterviewerRecord record) {
        Integer visitorId = record.getVisitorId();
        if (null == visitorId) {
            throw new BusinessException("未获取到访客id");
        }
        int visitorDoingCount = dao.getUnderInterviewCountByVisitorId(visitorId);
        if (visitorDoingCount > 0) {
            throw new BusinessException("您当前有未结束的提审/会见业务");
        }
        int mainResu = dao.insertInterviewerRecordMain(record);
        if (mainResu < 1) {
            throw new BusinessException("主记录新增失败");
        } else {
            List<InterviewerRecordDtl> records = record.getRecords();
            String[] prisonInNos = records.stream().map(r -> r.getPrisonInNo()).collect(Collectors.toList()).toArray(new String[]{});
            int prisonerDoingCount = dao.getUnderInterviewCountByPrisonInNos(prisonInNos);
            if (prisonerDoingCount > 0) {
                throw new BusinessException("所选对象中包含正在被提审/会见的对象");
            }
            records.forEach(r -> r.setIrmId(record.getId()));
            int dtlResu = dao.insertInterviewerRecordDtl(records);
            if (dtlResu < 1) {
                throw new BusinessException("子记录新增失败");
            } else {
                if (null != record.getRoomId()) {
                    Room room = roomService.selectRoomById(record.getRoomId());
                    if (room.getState() != 0) {
                        throw new BusinessException("房间已被占用");
                    }
                    room.setState(1);
                    room.setVisitorId(visitorId);
                    int roomResu = roomService.updateRoom(room);
                    if (roomResu < 1) {
                        throw new BusinessException("房间状态更改失败");
                    } else {
                        mqService.sendMessage(new MqMessageBean("arraign", "new-record", "", moduleName));
                        return true;
                    }
                } else {
                    return true;
                }
            }
        }
    }

    @Override
    @Transactional
    public synchronized int updateInterviewerRecord(InterviewerRecordDtl record) {
        Integer irmId = record.getIrmId();
        if (null == irmId) {
            throw new BusinessException("未获取到主记录id");
        } else {
            InterviewerRecord condition = new InterviewerRecord();
            condition.setId(irmId);
            List<InterviewerRecord> mainRecords = dao.list(condition);
            if (mainRecords.size() == 0) {
                throw new BusinessException("未获取到主记录");
            } else if (mainRecords.size() > 1) {
                throw new BusinessException("主记录数目异常");
            }
            InterviewerRecord mainRecord = mainRecords.get(0);
            List<InterviewerRecordDtl> dtls = mainRecord.getRecords();
            Optional<InterviewerRecordDtl> opt = dtls.stream().filter(d->d.getId().equals(record.getId())).findFirst();
            if(opt.isPresent()){
                InterviewerRecordDtl dtl = opt.get();
                if(record.getState() != 1 && record.getState() != 2){
                    throw new BusinessException("参数异常");
                }
                if(dtl.getState().equals(record.getState())){
                    throw new BusinessException("记录状态已更新，请勿重复操作");
                }
                if(dtl.getState() == 0 && record.getState() == 2){
                    throw new BusinessException("记录未开始，请先开始");
                }
                if(dtl.getState() == 2 && record.getState() == 1){
                    throw new BusinessException("记录已结束，请勿操作");
                }
            }else{
                throw new BusinessException("子记录获取失败");
            }
            int recordResu = dao.updateInterviewerRecordDtl(record);
            if(record.getState() == 2){
                mainRecords = dao.list(condition);
                InterviewerRecord mainRecordU = mainRecords.get(0);
                dtls = mainRecordU.getRecords();
                if (dtls.stream().filter(d -> d.getRoomId().equals(mainRecordU.getRoomId())).noneMatch(d -> d.getState() != 2)) {
                    Integer roomId = mainRecord.getRoomId();
                    Room room = new Room();
                    room.setArdId(roomId);
                    roomService.updateRoom(room);
                }
                BringRecord bringRecord = new BringRecord(record.getId());
                bringRecord.setType(1);
                bringRecordService.insertBringRecord(bringRecord);
                return recordResu;
            }else if(record.getState() == 1){
                BringRecord bringRecord = new BringRecord(record.getId());
                bringRecord.setType(0);
                bringRecordService.insertBringRecord(bringRecord);
                return recordResu;
            }else {
                return recordResu;
            }
        }
    }

    @Override
    @Transactional
    public boolean delInterviewerRecord(Integer id) {
        InterviewerRecord condition = new InterviewerRecord();
        condition.setId(id);
        List<InterviewerRecord> records = dao.list(condition);
        if (records.size() < 1) {
            throw new BusinessException("未获取到该记录");
        } else if (records.size() == 1) {
            InterviewerRecord recordMain = records.get(0);
            return this.delRecord(recordMain);
        } else {
            throw new BusinessException("记录数目异常");
        }
    }

    @Override
    @Transactional
    public boolean selfHelpDel(InterviewerRecord record) {
        String operationCode = record.getOperationCode();
        if (StringUtils.isEmpty(operationCode)) {
            throw new BusinessException("请输入操作码");
        } else {
            InterviewerRecord condition = new InterviewerRecord();
            condition.setId(record.getId());
            List<InterviewerRecord> records = dao.list(condition);
            if (records.size() > 0) {
                InterviewerRecord recordMain = records.get(0);
                if (operationCode.equals(recordMain.getOperationCode())) {
                    return this.delRecord(recordMain);
                } else {
                    throw new BusinessException("操作码不正确");
                }
            } else {
                throw new BusinessException("未查询到该记录");
            }
        }
    }

    @Override
    public List<Map<String, Object>> getInfosBuIrIds(String ids) {
        return dao.getInfosBuIrIds(Convert.toStrArray(ids));
    }

    private boolean delRecord(InterviewerRecord recordMain) {
        List<InterviewerRecordDtl> recordsDtls = recordMain.getRecords();
        Set<Integer> roomIds = new HashSet<>();
        Integer mainRoomId = recordMain.getRoomId();
        if (null != mainRoomId) {
            roomIds.add(mainRoomId);
        }
        recordsDtls.forEach(d -> {
            if (null != d.getRoomId())
                roomIds.add(d.getRoomId());
        });
        Room room = new Room();
        room.setVisitorId(recordMain.getVisitorId());
        roomIds.forEach(rId -> {
            room.setArdId(rId);
            if (roomService.updateRoom(room) < 1)
                throw new BusinessException("房间信息更新异常");
        });
        int mainResu = dao.delInterviewerRecordMain(recordMain.getId());
        if (mainResu < 1) {
            throw new BusinessException("主记录删除失败");
        } else {
            int dtlResu = dao.delInterviewerRecordDtls(recordMain.getId());
            if (dtlResu < 1) {
                throw new BusinessException("子记录删除失败");
            } else {
                return true;
            }
        }
    }

    /**
     * 查询提审会见主记录
     */
    public List<Map<String,Object>> interviewerMainRecordList(InterviewerRecord record){
        return dao.interviewerMainRecordList(record);
    }

    /**
     * 查询提审会见详细记录
     */
    public List<Map<String, Object>> interviewerDetisRecord(InterviewerRecordDtl recordDtl){
        return dao.interviewerDetisRecord(recordDtl);
    }

    public int lawyerEntry(String ip,Integer command){
        int state = command;
        if(command != 1 && command != 2){
            throw new BusinessException("按钮指令异常：未知指令："+command);
        }else{
            Room roomCondition = new Room();
            roomCondition.setIp(ip);
            List<Room> rooms = roomService.selectRoomList(roomCondition);
            if(rooms.size() == 1){
                Room _room = rooms.get(0);
                Map<String,Object> params = new HashMap<>();
                InterviewerRecord record = new InterviewerRecord();
                Integer roomId = _room.getArdId();
                params.put("noneState",2);
                params.put("roomId",roomId);
                record.setParams(params);
                List<InterviewerRecord> records  = dao.list(record);
                if(records.size() == 1){
                    InterviewerRecord recordMain = records.get(0);
                    if(recordMain.getType() == 1){
                        List<InterviewerRecordDtl> dtls = recordMain.getRecords();
                        if(dtls == null){
                            throw new BusinessException("未获取到子记录");
                        }else if(dtls.size() == 1){
                            InterviewerRecordDtl dtl = dtls.get(0);
                            dtl.setState(state);
                            Date now = new Date();
                            if(state == 1){
                                dtl.setBeginTime(now);
                            }else{
                                dtl.setEndTime(now);
                            }
                            return this.updateInterviewerRecord(dtl);
                        }else{
                            throw new BusinessException("子记录数目异常");
                        }
                    }else{
                        throw new BusinessException("采访类型不匹配，应为会见类型");
                    }
                }else{
                    throw new BusinessException("记录数目异常");
                }
            }else if(rooms.size() == 0){
                throw new BusinessException("未知的按钮ip");
            }else {
                throw new BusinessException("按钮ip对应多个房间，请检查ip设置");
            }
        }
    }

    @Override
    public List<Map<String, Object>> selectBringRecordListByAreaNo(Integer areaNo) {
        return dao.selectBringRecordListByAreaNo(areaNo);
    }
}
